import { constantRoutes } from '@/router'
import { getRouters,routepathList,getChildren } from '@/api/menu'
import Layout from '@/layout/index'
import router from '@/router'
import ParentView from '@/components/ParentView'
import {loadPage} from '@/api/loadPage'
const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise((resolve, reject) => {
        // 向后端请求路由数据
        getRouters().then(res => {
//		  const res= getRouters();
//		  res.rows.filter(route => {
//			if (route.url){
//				routepathList.push("/"+route.url);			
//			}
//		  })
          const accessedRoutes = filterAsyncRouter(res.data[0].children,1)
//		  accessedRoutes=getChildren(accessedRoutes,"09EFE9359D46440E812D5FAD62C544E9","pid");
          accessedRoutes.push({ path: '*', redirect: '/404', hidden: true });
		  console.log(accessedRoutes);
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
          .catch(err => {
			throw err;
            })
      })
    }
  }
}

let rindex=0
//let tree_level=1
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap,tree_level) {
  return asyncRouterMap.filter(route => {
	rindex++;
	if (route.name=="/"){
		route.name="path"+rindex;
	}

	if (typeof(route.path)=="undefined"||route.path=="/"){
		route.path="path"+rindex;
	}
	if (route.path){
		routepathList.push(route.path);			
	}
    if (route.children != null && route.children && route.children.length) {
	  if (tree_level === 1) {
        route.component = Layout
      }else{
		route.component = ParentView
		}
      route.children = filterAsyncRouter(route.children,2)
    }else if (route.component) {
      // Layout组件特殊处理
        route.component = (resolve) =>loadPage(route.path,resolve);
    }
    return true
  })
}

export default permission
